package com.example.logisticsingle.authorization;


import com.example.logisticsingle.String.StringUtils;
import com.example.logisticsingle.constants.Config;
import com.example.logisticsingle.constants.ResponseEnum;
import com.example.logisticsingle.dto.Result;
import com.example.logisticsingle.utils.JsonUtils;
import com.example.logisticsingle.utils.ResultUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 未登录验证处理

 *
 */
public class UnAuthorizedEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        String str = request.getHeader(Config.REQUEST_TYPE);
        String request_type = StringUtils.isNull(str)?request.getParameter(Config.REQUEST_TYPE):str;
        if(StringUtils.isNotNull(request_type) && Integer.valueOf(request_type)==Config.REQUEST_TYPE_WEB) {
            String referer = request.getRequestURI();
            String login_url = request.getContextPath()+"/login";
            String redit_url = (referer==login_url)? login_url:String.format("%s?%s=%s", login_url,Config.REDIRECT_URL,request.getRequestURL().toString());
            response.sendRedirect(redit_url);
        }else {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            Result<?> result = ResultUtils.failure(ResponseEnum.USER_UNLOGIN);
            response.getWriter().write(JsonUtils.toJson(result));
        }

    }
}
